package com.chizha.iot.mqtt.client;
/**
*
* Description:
* @author admin
* 2017-11-9 17:50:15
*/

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class ClientMQTT extends Thread {

	public static final String HOST = "tcp://210.77.68.221:10020";
	// public static final String TOPIC = "topic11";
	// public static final String TOPIC1 = "topic112";
	private static Log logger = Log.getLog(ClientMQTT.class);

	private boolean isBroken = true;
	private static String clientid = "";
	private MqttClient client;
	private MqttConnectOptions options;
	private String userName = "admin";
	private String passWord = "qiaojiaoshou123";
	private static ClientMQTT instance = new ClientMQTT();
	public static ClientMQTT getInstance()
	{
		return instance;
	}
	private ClientMQTT()
	{
		
	}
	private static Log log = Log.getLog(ClientMQTT.class);

	public static void main(String[] args)
	{
		ClientMQTT instance = ClientMQTT.getInstance();
		instance.start();
	}
	
	@Override
	public void run() {
		InetAddress addr = null;
		String ip = "";
		String address = "";
		boolean result = false;

		try {
			addr = InetAddress.getLocalHost();
			ip = addr.getHostAddress().toString();// 获得本机IP
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			ip = "0.0.0.0";
		}
		address = addr.getHostName().toString();// 获得本机名称
		clientid = address + String.valueOf(Calendar.getInstance().getTimeInMillis());
		while (true)
		{
			try {
				if (isBroken)
				{
					result = init();
					if (result == true)
					{
						isBroken = false;
					}
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				isBroken = true;
			}			
			
			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private boolean init() {

		logger.error("---------------Init MQTT client-----------------");
		try {
			// host为主机名，clientid即连接MQTT的客户端ID，一般以唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
			client = new MqttClient(HOST, clientid, new MemoryPersistence());
			// MQTT的连接设置
			options = new MqttConnectOptions();
			// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
			options.setCleanSession(true);
			// 设置连接的用户名
			options.setUserName(userName);
			// 设置连接的密码
			options.setPassword(passWord.toCharArray());
			// 设置超时时间 单位为秒
			options.setConnectionTimeout(30);
			// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
			options.setKeepAliveInterval(60);
			options.setAutomaticReconnect(true);
			// 设置回调
			client.setCallback(new PushCallback());
			// MqttTopic topic = client.getTopic(TOPIC);
			// setWill方法，如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
			// options.setWill(topic, "close".getBytes(), 2, true);
			// 查询所有topic
			String[] topicNames = getTopicName();
			client.connect(options);
			// 订阅消息
			int[] Qos = new int[topicNames.length];
			for (int i = 0; i < topicNames.length; i++) {
				Qos[i] = 1;
			}
			String[] topic1 = topicNames;
			client.subscribe(topic1, Qos);
		} catch (Exception e) {
			try {
				client.close();
			} catch (MqttException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}			
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private static String[] getTopicName() {
		String sql = "select terminal_id from terminal";
		List<Record> terminalList = new ArrayList<Record>();
		terminalList = Db.find(sql);

		String[] topicNames = new String[terminalList.size() * 2];
		int listSize = terminalList.size();
		String deviceID = "";
		for (int i = 0; i < listSize; i++) {
			deviceID = terminalList.get(i).getStr("terminal_id");
			topicNames[i] = deviceID + "/picup";
			topicNames[i + listSize] = deviceID + "/msgup";
		}
		return topicNames;
	}
	
	private static String[] getTopicName2() {
		String[] topicNames = new String[1];
		topicNames[0] = "123";
		return topicNames;
	}
	
	public void reconnect() {
		logger.error("-------------------reconnect--------------------");
//		try {
//			client.close();
//		} catch (MqttException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		//instance = new ClientMQTT();
		//instance.start();
		//isBroken  = true;
	}
}
